/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI_SIFACT;

import AccesoBusquedas.AB_Inventario;
import AccesoDatosAvanzado.AD_Producto_Inventario;
import AccesoDatosSimple.cProducto_Inventario;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import sifact.conexion.cConexion;

/**
 *
 * @author Cyber Huevadictos
 */
public class Frm_Inventario extends javax.swing.JDialog {

    private AB_Inventario obj;
    private String objcadena = "";
    private String txtnulos = "Los Campos Vacios son:\n";
    String[] tupla = new String[5];

    /**
     * Creates new form Frm_Inventario
     */
    public Frm_Inventario(java.awt.Frame parent, boolean modal) throws Exception {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        //
        obj = new AB_Inventario();
        jTableBusqueda.setModel(obj.TInventario(null, 0));
        jTableBusqueda.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //evento escuchador
        jTableBusqueda.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    @Override
                    public void valueChanged(ListSelectionEvent event) {
                        try {
                            jTableAccion(event);
                        } catch (Exception ex) {
                            Logger.getLogger(Frm_Inventario.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
    }

    private void jTableAccion(javax.swing.event.ListSelectionEvent evt) throws Exception {
        int filas = jTableBusqueda.getSelectedRow();
        this.objcadena = jTableBusqueda.getValueAt(filas, 1).toString();        
        tupla = AD_Producto_Inventario.BuscarCodigo(this.objcadena);
        jTextFieldCantMin.setText(tupla[1]);
        jTextFieldCantMax.setText(tupla[2]);
    }

    private boolean CamposNulos() {
        boolean band = false;

        if (jTextFieldCantMin.getText().trim().equals("")) {
            txtnulos = txtnulos + "CANTIDAD MINIMA\n";
            band = true;
        }
        if (jTextFieldCantMax.getText().trim().equals("")) {
            txtnulos = txtnulos + "CANTIDAD ACTUAL\n";
            band = true;
        }

        return band;
    }

    private void DatosFormulario(cProducto_Inventario obj) {       

        //datos para la tabla PRODUCTO_INVENTARIO
        obj.setNumIDProducto(Integer.parseInt(this.objcadena));
        obj.setDateFechaCompra(tupla[3]);
        obj.setNumCantMin(Double.parseDouble(jTextFieldCantMin.getText()));
        obj.setNumCantActual(Double.parseDouble(jTextFieldCantMax.getText()));
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelBotones = new javax.swing.JPanel();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();
        jLabelNombre = new javax.swing.JLabel();
        jTextFieldNombre = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldCantMin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCantMax = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableBusqueda = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("INVENTARIO DE PRODUCTOS");

        jPanelBotones.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButtonAceptar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/16px-Crystal_Clear_action_apply.png"))); // NOI18N
        jButtonAceptar.setText("ACEPTAR");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/16px-Crystal_Clear_action_button_cancel.png"))); // NOI18N
        jButtonCancelar.setText("CANCELAR");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelBotonesLayout = new javax.swing.GroupLayout(jPanelBotones);
        jPanelBotones.setLayout(jPanelBotonesLayout);
        jPanelBotonesLayout.setHorizontalGroup(
            jPanelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBotonesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonAceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
                .addComponent(jButtonCancelar)
                .addContainerGap())
        );
        jPanelBotonesLayout.setVerticalGroup(
            jPanelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBotonesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAceptar)
                    .addComponent(jButtonCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabelNombre.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabelNombre.setText("NOMBRE:");

        jTextFieldNombre.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldNombre.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextFieldNombreCaretUpdate(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("CANTIDAD MINIMA:");

        jTextFieldCantMin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldCantMin.setText("0.00");
        jTextFieldCantMin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextFieldCantMinKeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("CANTIDAD ACTUAL:");

        jTextFieldCantMax.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldCantMax.setText("0.00");
        jTextFieldCantMax.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextFieldCantMaxKeyTyped(evt);
            }
        });

        jTableBusqueda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTableBusqueda);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jTextFieldCantMin, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18)
                                        .addComponent(jTextFieldCantMax, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(142, 142, 142))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jPanelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(80, 80, 80))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelNombre)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNombre)
                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldCantMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldCantMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed

        //codigo para realizar las diferentes tareas Insert,Update,Delete
        Exception e;
        if (CamposNulos() == true) {//verifico que campo se encuentra vacio y advierto
            JOptionPane.showMessageDialog(null, txtnulos, "Campos Vacios", JOptionPane.INFORMATION_MESSAGE);
            txtnulos = "Los Campos Vacios son:\n";
        } else {//Inicio la Insercion            

            cProducto_Inventario obj = new cProducto_Inventario();
            //Lleno los datos del formulario
            DatosFormulario(obj);
            try {
                e = AD_Producto_Inventario.Actualizar(obj);

                if (e == null) {
                    JOptionPane.showMessageDialog(null, "Se ha sido modificado correctamente", "MODIFICAR", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Existe el siguiente error:\n" + e, "ERROR AL MODIFICAR", JOptionPane.ERROR_MESSAGE);
                }
                //dispose();
                cConexion.cerrar();
            } catch (Exception ex) {
                Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
            }
        }//Terminamos con la Insercion            

    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        try {
            // TODO add your handling code here:
            dispose();
            cConexion.cerrar();
        } catch (Exception ex) {
            Logger.getLogger(Frm_Clientes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jTextFieldCantMinKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCantMinKeyTyped
        // TODO add your handling code here:
        char t = evt.getKeyChar();
        if (!((t >= '0' && t <= '9') || t == '.') || jTextFieldCantMin.getText().length() > 6) {
            evt.setKeyChar('\b');
        }
    }//GEN-LAST:event_jTextFieldCantMinKeyTyped

    private void jTextFieldCantMaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCantMaxKeyTyped
        // TODO add your handling code here:
        char t = evt.getKeyChar();
        if (!((t >= '0' && t <= '9') || t == '.') || jTextFieldCantMax.getText().length() > 6) {
            evt.setKeyChar('\b');
        }
    }//GEN-LAST:event_jTextFieldCantMaxKeyTyped

    private void jTextFieldNombreCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextFieldNombreCaretUpdate
        // TODO add your handling code here:
        try {
            jTableBusqueda.setModel(obj.TInventario(this.jTextFieldNombre.getText().trim().toUpperCase(), 1));
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jTextFieldNombreCaretUpdate

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frm_Inventario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frm_Inventario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frm_Inventario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frm_Inventario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Frm_Inventario dialog = new Frm_Inventario(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        @Override
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                } catch (Exception ex) {
                }
                //new Frm_Inventario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelNombre;
    private javax.swing.JPanel jPanelBotones;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableBusqueda;
    private javax.swing.JTextField jTextFieldCantMax;
    private javax.swing.JTextField jTextFieldCantMin;
    private javax.swing.JTextField jTextFieldNombre;
    // End of variables declaration//GEN-END:variables
}
